package samples;

import java.net.URL;

import de.fmui.spheon.jsoap.Envelope;
import de.fmui.spheon.jsoap.Fault;
import de.fmui.spheon.jsoap.ParamBag;
import de.fmui.spheon.jsoap.RPCCall;
import de.fmui.spheon.jsoap.SoapConfig;
import de.fmui.spheon.jsoap.transport.http.SoapHttpClient;

public class SampleClient
{
	public SampleClient()
	{
		doIt();
	}
	
	public void doIt()
	{
		// get configuration
		SoapConfig sc = new SoapConfig();
		// set the actor for fault messages
		sc.setActor("/sample/client");		
		
		// prepare a call
		RPCCall call = new RPCCall(	/* SoapConfig */ sc,
									/* namespace */  "urn:mySampleService", 
									/* method */     "sampleMethod");


		// set parameters
		try {
			call.setParameter(	/* name */  "mystring", 
								/* value */ "sample",
								/* type */  String.class);
			call.setParameter(	/* name */  "count",
								/* value */  new Integer(5),
								/* type */   int.class);

			// execute call (via HTTP)
		    SoapHttpClient shc = new SoapHttpClient(sc);
		    Envelope answer = shc.invokeHTTP(
		            /* server */    new URL("http://localhost:8080/spheon-jsoap/RPC"),
		            /* SOAPAction*/ "",  
		            /* envelope */  call.getEnvelope());
		             
			// check for a fault message
			if(answer.hasFault()) {
				Fault f = answer.getFault();
				System.out.println("Faultcode:   " + f.getFaultcode());
				System.out.println("Faultstring: " + f.getFaultstring());
				System.out.println("Faultactor:  " + f.getFaultactor());		
				return;
			}
		
			// get the results
			ParamBag p = call.getResults(answer);
		
			// display the results
			for(int i=0; i<p.size(); i++) {
				System.out.print(p.getName(i) + "\t");
				System.out.print(p.getType(i).getName() + "\t");
				System.out.print(p.getValue(i) + "\n");
			}
			
			// If we know, the first return value is a string ...
			String result = (String) p.getValue(0);
			System.out.println("Result: " + result);
			
		}
		catch(Exception e) {
			System.out.println("Exception: " + e);
			e.printStackTrace();
		}	
	}
	
	public static void main(String[] args) 
	{
		new SampleClient();
	}		
}